package com.cade.agriculturemall.view.personalCenter.discount.storeDiscountFragment;

import android.text.TextUtils;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.provider.DataLoadProviderRegistry;
import com.cade.agriculturemall.base.BasePresenter;
import com.cade.agriculturemall.model.Ticket;
import com.cade.agriculturemall.model.UserInfoEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hshunxin on 2018/2/27.
 */

public class StoreDiscountPresenter extends BasePresenter<StoreDiscountContract.IView> implements StoreDiscountContract.IPresenter {
    public StoreDiscountPresenter(StoreDiscountContract.IView view) {
        super(view);
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    AVQuery<Ticket> entityAVQuery = new AVQuery<>("ticket_discount");

    @Override
    public void downTicket() {
        final Date date=new Date();
        final SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");

        final List<Ticket> myDiscountList = new ArrayList<>();
        final List<Ticket> storeList = new ArrayList<>();
        entityAVQuery.findInBackground(new FindCallback<Ticket>() {
            @Override
            public void done(List<Ticket> list, AVException e) {
                if (e == null) {
                    for (Ticket entity : list) {
                        if (TextUtils.isEmpty(entity.getUserId()) || entity.getUserId() == null) {
                            int i=date.compareTo(entity.getEndTime());
                            if(i<0)
                            storeList.add(entity);
                        } else {
                            myDiscountList.add(entity);
                        }
                    }
                    mView.getStoreTicket(storeList);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
    String currentUserId = user.getObjectId();

    @Override
    public void gainTicket(String ticketId) {
        AVObject avObject = AVObject.createWithoutData("ticket_discount", ticketId);
        avObject.put("user_id", currentUserId);
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    mView.showMessage("添加成功！");
                } else {
                    e.printStackTrace();
                }
            }
        });
    }
}
